<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>websocket通讯</title>
</head>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
    var socket;

    var userId;
    window.onload=function openSocket() {

        userId=document.getElementById("userId")
        userId.innerHTML=Math.ceil(Math.random()*200)
        if(typeof(WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        }else{
            console.log("您的浏览器支持WebSocket");
            //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
            //等同于socket = new WebSocket("ws://localhost:8888/xxxx/im/25");
            // var socketUrl="ws://localhost:8090/api/pushMessage/"+$("#userId").val();
            var socketUrl="http://localhost:8090/api/pushMessage/"+ userId;
            socketUrl=socketUrl.replace("https","ws").replace("http","ws");
            console.log(socketUrl);
            if(socket!=null){
                socket.close();
                socket=null;
            }
            socket = new WebSocket(socketUrl);
            //打开事件
            socket.onopen = function() {
                console.log("websocket已打开");
                //socket.send("这是来自客户端的消息" + location.href + new Date());
            };
            //获得消息事件
            socket.onmessage = function(event) {
                console.info(event.data)
                console.info(isJson(event.data))
                //var msg;
                //var content=document.getElementById("content")
                //if(isJson(event.data)){
                //    msg=JSON.parse(event.data);
                //	if(msg.userList){
                //		var onlineUsers=document.getElementById("onlineUsers")
                //		onlineUsers.innerHTML=""
                //		for(var item in msg.userList) {
                //			onlineUsers.innerHTML= onlineUsers.innerHTML+"<input type='checkbox' name='onlineCheckBox' value="+msg.userList[item]+">" + msg.userList[item] +"</br>"
                //			console.info("在线用户列表"+msg.userList[item] )
                //		}
                //	}else{
                //		content.innerHTML=content.innerHTML+msg.userId  +":    " +msg.contentText + "</br>"
                //	}
                //}else{
                //	content.innerHTML=content.innerHTML+ event.data  +"</br>"
                //}
                //content.scrollTop = content.scrollHeight;


                //发现消息进入    开始处理前端触发逻辑
            };
            //关闭事件
            socket.onclose = function() {
                console.log("websocket已关闭");
            };
            //发生了错误事件
            socket.onerror = function() {
                console.log("websocket发生了错误");
            }
        }
    }

    //判断是否为json串
    function isJson($string)
    {
        try {
            if(typeof JSON.parse($string) == 'object')
                return true;
            return false;
        } catch (e) {
            console.log(e);
            return false;

        }
    }

    function sendMessage() {
        if(typeof(WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        }else {

            console.info(fun().length!=0)
            if(fun().length!=0){

                console.info('{"privateUsers":"'+check_val +  '"userId":"'+userId.innerHTML+'","contentText":"'+$("#contentText").val()+'"}');
                socket.send('{"privateUsers":"'+ check_val + '","userId":"'+userId.innerHTML+'","contentText":"'+$("#contentText").val()+'"}');
                console.info(check_val)
            }else{

                console.log("您的浏览器支持WebSocket");
                console.log('{"userId":"'+userId.innerHTML+'","contentText":"'+$("#contentText").val()+'"}');
                socket.send('{"userId":"'+userId.innerHTML+'","contentText":"'+$("#contentText").val()+'"}');
            }

        }
    }



    //获取选中的checkbox
    function fun(){
        obj = document.getElementsByName("onlineCheckBox");
        check_val = [];
        for(k in obj){
            if(obj[k].checked)
                check_val.push(obj[k].value);
        }
        return check_val
    }
</script>
<body>
<div id="content"  style="overflow:auto; height: 200px; width: 400px; border: 1px solid #999;" > </div>
<p>【UserId:】<span id="userId"></span></p>
<div>【内容:】<input id="contentText" name="contentText" type="text" value="hello websocket"></div>
<p>【操作】：<button onclick="sendMessage()">发送</button>
<h4>在线用户列表</h4>
<div id="onlineUsers"><div>

</body>

</html>

